package com.guguskins.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guguskins.back.common.exception.GlobalMsgException;
import com.guguskins.back.entity.GuBoxItem;
import com.guguskins.back.entity.GuGoods;
import com.guguskins.back.entity.bo.ContractGoodsBo;
import com.guguskins.back.entity.vo.PageVo;
import com.guguskins.back.mapper.GuGoodsMapper;
import com.guguskins.back.service.GuBoxItemService;
import com.guguskins.back.service.GuGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 饰品表 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-05-14
 */
@Service
public class GuGoodsServiceImpl extends ServiceImpl<GuGoodsMapper, GuGoods> implements GuGoodsService {

    @Autowired
    private GuGoodsMapper goodsMapper;

    @Autowired
    private GuBoxItemService boxItemService;

    @Override
    public List<GuGoods> getGoodsList(long boxId) {
        return goodsMapper.getGoodsList(boxId);
    }

    @Override
    public List<GuGoods> getGoodsListByRollId(long rollId, int state) {
        List<GuGoods> goodsList;
        if (state == 2) {
            goodsList = goodsMapper.getDetailGoodsListByRollId(rollId, null);
        } else {
            goodsList = goodsMapper.getGoodsListByRollId(rollId);
        }
        return goodsList;
    }

    @Override
    public List<GuGoods> getGoodsListByRollId(long rollId, String searchKey) {
        return goodsMapper.getDetailGoodsListByRollId(rollId, searchKey);
    }

    /**
     * 计算爆率，格式化数据（给前端）
     */
    @Override
    public List<GuGoods> calculationRate(List<GuGoods> goodsList) {
        List<GuGoods> result = new ArrayList<>();
        //获取总概率
        BigDecimal totalProbability = goodsList.stream().map(GuGoods::getProbability).reduce(BigDecimal.ZERO, BigDecimal::add);

        //计算概率
        goodsList.forEach(goods -> goods.setExplodeRate(goods.getProbability().divide(totalProbability, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString() + "%"));

        //分组
        Map<String, List<GuGoods>> collect = goodsList.stream().collect(Collectors.groupingBy(GuGoods::getGoodsSameId, LinkedHashMap::new, Collectors.toList()));

        //获取分组后的key（key = 饰品同一id）
        Set<String> sameIds = collect.keySet();

        //提取公共参数信息
        sameIds.forEach(sameId -> {
            GuGoods goods = new GuGoods();
            List<GuGoods> subGoodsList = collect.get(sameId);
            goods.setGoodsSameId(sameId);
            goods.setGoodsShortName(subGoodsList.get(0).getGoodsShortName());
            goods.setGoodsOriginalIconUrl(subGoodsList.get(0).getGoodsOriginalIconUrl());
            goods.setGoodsIconUrl(subGoodsList.get(0).getGoodsIconUrl());
            goods.setGoodsLevel(subGoodsList.get(0).getGoodsLevel());
            goods.setGoodsPrice(subGoodsList.stream().max(Comparator.comparing(GuGoods::getGoodsPrice)).orElse(new GuGoods()).getGoodsPrice());
            /*BeanCopier copier = BeanCopier.create(GuGoods.class, GuGoods.class, false);
            copier.copy(subGoodsList.get(0), goods, null);*/
            goods.setSubGoodsList(subGoodsList);
            goods.setGoodsPriceType(subGoodsList.stream().max(Comparator.comparing(GuGoods::getGoodsPriceType)).orElse(new GuGoods()).getGoodsPriceType());
            BigDecimal subTotal = subGoodsList.stream().map(GuGoods::getProbability).reduce(BigDecimal.ZERO, BigDecimal::add);
            goods.setExplodeRate(subTotal.divide(totalProbability, 5, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString() + "%");
            result.add(goods);
        });
        return result;
    }

    @Override
    public List<GuGoods> format(List<GuGoods> goodsList) {
        List<GuGoods> result = new ArrayList<>();

        //分组
        Map<String, List<GuGoods>> collect = goodsList.stream().collect(Collectors.groupingBy(GuGoods::getGoodsSameId, LinkedHashMap::new, Collectors.toList()));

        //获取分组后的key（key = 饰品同一id）
        Set<String> sameIds = collect.keySet();

        //提取公共参数信息
        sameIds.forEach(sameId -> {
            GuGoods goods = new GuGoods();
            List<GuGoods> subGoodsList = collect.get(sameId);
            goods.setGoodsSameId(sameId);
            goods.setGoodsShortName(subGoodsList.get(0).getGoodsShortName());
            goods.setGoodsOriginalIconUrl(subGoodsList.get(0).getGoodsOriginalIconUrl());
            goods.setGoodsIconUrl(subGoodsList.get(0).getGoodsIconUrl());
            goods.setGoodsLevel(subGoodsList.get(0).getGoodsLevel());
            goods.setGoodsPrice(subGoodsList.stream().max(Comparator.comparing(GuGoods::getGoodsPrice)).orElse(new GuGoods()).getGoodsPrice());
            /*BeanCopier copier = BeanCopier.create(GuGoods.class, GuGoods.class, false);
            copier.copy(subGoodsList.get(0), goods, null);*/
            goods.setSubGoodsList(subGoodsList);
            result.add(goods);
        });
        return result;
    }

    @Override
    public PageVo<GuGoods> backPage(int p, int size, String searchKey) {
        Page<GuGoods> page = new Page<>(p, size);
        LambdaQueryWrapper<GuGoods> lqw = new LambdaQueryWrapper<>();
        lqw.like(!ObjectUtils.isEmpty(searchKey), GuGoods::getGoodsName, searchKey);
        Page<GuGoods> pageResult = this.page(page, lqw);
        return new PageVo<>(pageResult.getRecords(), pageResult.getTotal());
    }

    @Override
    public boolean changePrice(GuGoods goods) {
        GuGoods guGoods = this.getById(goods.getGoodsId());
        if (guGoods.getGoodsPrice().compareTo(goods.getOldGoodsPrice()) != 0) {
            throw new GlobalMsgException("原始价格被改动，请刷新");
        }
        return goods.updateById();
    }

    @Override
    public PageVo<GuGoods> backContractGoodsPage(int p, int size, String searchKey) {
        int index = (p - 1) * size;
        List<GuGoods> goodsList = goodsMapper.getContractGoodsPageDate(index, size, searchKey);
        long total = goodsMapper.getContractGoodsPageTotal(searchKey);
        return new PageVo<>(goodsList, total);
    }

    @Override
    public boolean backContractAdd(ContractGoodsBo contractGoodsBo) {
        if (CollectionUtils.isEmpty(contractGoodsBo.getGoodsIds())) {
            return false;
        }
        contractGoodsBo.getGoodsIds().forEach(goodsId -> {
            GuBoxItem boxItem = new GuBoxItem();
            boxItem.setBoxId(-1L);
            boxItem.setItemId(goodsId);
            boxItem.setState(1);
            boxItem.insert();
        });
        return true;
    }

    @Override
    public boolean backContractChangeState(GuGoods goods) {
//        GuBoxItem boxItem = new GuBoxItem();
//        boxItem.setId(goods.getBiId());
//        boxItem.setState(goods.getState());
//        return boxItem.updateById();
        return boxItemService.removeById(goods.getBiId());
    }

}
